#include <WiFi.h>
#include <HTTPClient.h>
#include <UrlEncode.h>
#include "Arduino.h"
#include "WiFiMulti.h"
#include "Audio.h"


#include "global_config.h"
#include "baidu_authen.h"

void tts_get();
void player();


Audio audio;
WiFiMulti wifiMulti;

String url = TTS_URL;
String token;

void setup() {
  Serial.begin(115200);

  //1. 链接Wifi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  
  
  //首先，进行鉴权，取得所谓的 token，并打印出相关的结果来
  getBaiduToken();
  
  //encodedText 待转换为音频的文字
  encodedText = urlEncode(urlEncode(encodedText));


  //得到对应的音频文件
  tts_get();
  player();
}



void tts_get() {
  const char *headerKeys[] = { "Content-Type", "Content-Length" };
  // 5、修改百度语音助手的token
  //以下内容各自代表什么意思？
  //url += "?tok=24.e169f864a91715325118.282335-57722200";//这个是什么？
  url += "?tok=" + token;
  url += "&tex=" + encodedText;
  url += "&lan=zh";
  url += "&ctp=1";
  url += "&cuid=esp32s3"; //这里是不是应该改？？？？（用户唯一标识，用来计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码，长度为60字符以内）

  //以下为选填选项
  url += "&per=" + String(PER);
  url += "&spd=" + String(SPD);
  url += "&pit=" + String(PIT);
  url += "&vol=" + String(VOL);
  url += "&aue=" + String(AUE);

  HTTPClient http;

  //Serial.print("URL: ");
  //Serial.println(url);

  http.begin(url);
  http.collectHeaders(headerKeys, 2);
  int httpResponseCode = http.GET();
  if (httpResponseCode > 0) {
    if (httpResponseCode == HTTP_CODE_OK) {
      Serial.print("Content-Type = ");
      Serial.println(http.header("Content-Type"));
      String contentType = http.header("Content-Type");
      if (contentType.startsWith("audio")) 
      {
        Serial.println("合成成功，返回的是音频文件");
        // 处理音频文件，保存到SD卡或者播放
        //但是此处并没有进行处理？？？
      } 
      else if (contentType.equals("application/json")) 
      {
        Serial.println("合成出现错误，返回的是JSON文本");
        // 处理错误信息，根据需要进行相应的处理
      } else 
      {
        Serial.println("未知的Content-Type");
        // 可以添加相应的处理逻辑
      }
    } else {
      Serial.println("Failed to receive audio file");
    }
  } else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  http.end();
}



void loop() {

  audio.loop();
  if (Serial.available()) {  // put streamURL in serial monitor
    audio.stopSong();
    String r = Serial.readString();
    r.trim();
    if (r.length() > 5) audio.connecttohost(r.c_str());
    log_i("free heap=%i", ESP.getFreeHeap());
  }
}



void player() {
  // WiFi.mode(WIFI_STA);
  // wifiMulti.addAP(ssid.c_str(), password.c_str());
  // wifiMulti.run();
  // if(WiFi.status() != WL_CONNECTED){
  //     WiFi.disconnect(true);
  //     wifiMulti.run();
  // }
  const char *host_url = url.c_str(); //其中url是 申请的链接
  audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
  audio.setVolume(21);        // 0...21
  audio.connecttohost(host_url);  //  128k mp3 //host 为 https://tsn.baidu.com/text2audio
  
}



